package com.example.first.thread;

import java.sql.Time;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author LSQ
 * @Description 练习Reentrantlock 加 runnable
 * @date 2021/11/5 21:43
 * @Version 1.0
 */

public class Task implements Runnable {

    private String taskName;
    private CountDownLatch countDownLatch;

    public Task(String taskName) {
        this.taskName = taskName;
    }

    public Task(String taskName, CountDownLatch countDownLatch) {
        this.taskName = taskName;
        this.countDownLatch = countDownLatch;
    }

    public String getTaskName() {
        return taskName;
    }

    public void setTaskName(String taskName) {
        this.taskName = taskName;
    }

    private static ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {

        System.out.println(Thread.currentThread().getName() + " start task name " + taskName);

        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " get lock!!");

            // 业务逻辑
            try {

                Random random = new Random();
                TimeUnit.SECONDS.sleep(random.nextInt(6));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        } finally {
            System.out.println(Thread.currentThread().getName() + " unlock!");
            lock.unlock();
        }

        System.out.println(Thread.currentThread().getName() + " end task name " + taskName);
        countDownLatch.countDown();

    }
}
